# coding: utf-8
require "selenium-webdriver"
require "rspec"
require "yaml"
require 'socket'
include RSpec::Expectations

# 载入登录模块
require File.expand_path("../../module/login", __FILE__)
include Login

# 加载配置文件
client_id = IPSocket.getaddress(Socket.gethostname)

if client_id == "192.168.6.227" then
  $basic_config = YAML.load(File.open(File.expand_path("../../config/config.yml", __FILE__)))
else
  $basic_config = YAML.load(File.open(File.expand_path("../../config/test_config.yml", __FILE__)))
end

# 获取登录配置数据
$config = $basic_config['config']
$user = $basic_config['user']
$project = $basic_config['project']
$projects = $basic_config['projects']
$merge = $basic_config['merge']
$comment = $basic_config['comment']

# 执行所有测试用例时进行的初始化
# 不传递参数时，为user_one用户登录
# 传递false时，为不登录
# 参数格式为$user['one']、$user['two']...
def before_setup(login_user = $user['one'])
  #@capa = Selenium::WebDriver::Remote::Capabilities.firefox
  #@capa[:firefox_binary] = "D:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe"
  #@driver = Selenium::WebDriver.for :remote, :url => 'http://'+$config['selenium_client_ip']+':4444/wd/hub', :desired_capabilities => @capa

  @driver = Selenium::WebDriver.for :remote, :url => 'http://'+$config['selenium_client_ip']+':4444/wd/hub', :desired_capabilities => :firefox
  @driver.manage.window.maximize
  @base_url = $config['web_url']
  @accept_next_alert = true
  @driver.manage.timeouts.implicit_wait = 10
  @verification_errors = []

  # 放在hash中，以便类里面调用
  @basic_hash = {
    'driver' => @driver,
    'base_url' => @base_url,
    'accept_next_alert' => @accept_next_alert,
    'verification_errors' => @verification_errors
  }

  # 默认使用uer_one登录
  if login_user then
    web_login(login_user)
  end
end

# 执行所有测试用例之后的操作
def after_setup
	@driver.quit
    @verification_errors.should == []
end

# 查找某个元素
def element_present?(how, what)
	@driver.find_element(how, what)
	true
rescue Selenium::WebDriver::Error::NoSuchElementError
	false
end

# 跳转到alert页面
def alert_present?()
	@driver.switch_to.alert
	true
rescue Selenium::WebDriver::Error::NoAlertPresentError
	false
end

#断言
def verify(&blk)
	yield
rescue ExpectationNotMetError => ex
	@verification_errors << ex
end

def close_alert_and_get_its_text
	alert = @driver.switch_to().alert()
	# alert_text = alert.text
	if (@accept_next_alert) then
		alert.accept()
	else
		alert.dismiss()
	end
	# alert_text
ensure
	@accept_next_alert = true
end


require File.expand_path("../func_helper", __FILE__)
require File.expand_path("../goto_helper", __FILE__)

